package com.hgsoft.pubsv.component.base.redis;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import com.google.common.collect.ImmutableList;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class RedisScriptUtil extends RedisCommon {

	private static final String SCRIPT_PREFIX = "SCRIPT:";

	/**
	 * lua限流脚本
	 * 
	 * @return
	 */
	public static String LIMIT_LUS_SCRIPT = "local c" + "\nc = redis.call('get',KEYS[1])"
			+ "\nif c and tonumber(c) > tonumber(ARGV[1]) then" + "\n return c;" + "\nend"
			+ "\nc = redis.call('incr',KEYS[1])" + "\nif tonumber(c) == 1 then"
			+ "\nredis.call('expire',KEYS[1],ARGV[2])" + "\nend" + "\nreturn c;";

	/**
	 * 执行lua脚本
	 * 
	 * @param returnClass
	 *            响应类型
	 * @param key
	 * @param luaScript
	 * @param params
	 *            参数
	 * @return
	 */
	public <T> T executeScript(Class returnClass, String key, String luaScript, String... params) {
		ImmutableList<String> keys = ImmutableList.of(StringUtils.join(SCRIPT_PREFIX, key));
		RedisScript<T> redisScript = new DefaultRedisScript<>(luaScript, returnClass);
		T t = this.stringRedisTemplate.execute(redisScript, keys, params);
		log.info("script return t is {} for key={} and luaScript = {} and params = {}", t, key, luaScript, params);
		return t;
	}
}
